package com.dmall.chapter04.section01;

import com.dmall.chapter02.section09.Graph;

/**
 * 求一个图的联通分量
 * @author wx
 * @date 2020-02-24 21:16:41
 */
public class CC {

    private Graph G;
    private boolean[] visited;
    private int cccount = 0;

    public CC(Graph G) {
        this.G = G;
        this.visited = new boolean[G.V()];
        for (int v = 0; v < G.V(); v++) {
            if (!visited[v]) {
                dfs(v);
                cccount ++;
            }
        }
    }

    private void dfs(int v) {
        visited[v] = true;
        for (int w : G.adj(v)) {
            if (!visited[w]) {
                dfs(w);
            }
        }
    }

    public int count() {
        return cccount;
    }

    public static void main(String[] args) {
        String filename = CC.class.getClassLoader().getResource("g.txt").getPath();
        Graph g = new Graph(filename);
        CC cc = new CC(g);
        System.out.println(cc.count());
    }
}